﻿#region Copyright
/// <copyright>
/// Copyright (c) 2008 Ilia Shramko.
/// Released under the terms of the GNU General Public License.
/// </copyright>
#endregion

using System;
using System.Collections.Generic;
using System.Text;

using Osh.Epg;
using Osh.Media;

namespace Osh.Qwerty
{
	public class Channel : ChannelBase, IIptvChannel
	{
		private Guid _id;
		private int? _serverId;
		private int? _folderId;
		private string _logoId;

		public Channel(ChannelDatabase database, Guid id, Uri url, int? serverId, int? folderId, string name, string description,
			string logoId, int? channelNumber, int? audioIndex, int? volumeLevel)
			: base(database, CreateChannelUri(id))
		{
			_id = id;
			_serverId = serverId;
			_folderId = folderId;

			this.Name = name;
			this.SourceUrl = url;
			this.LogoId = logoId;
			if(!string.IsNullOrEmpty(description))
				this.Description = description;
			if(channelNumber != null)
				this.ChannelNumber = channelNumber;
			if(audioIndex != null)
				this.AudioIndex = audioIndex;
			if(volumeLevel != null)
				this.VolumeLevel = volumeLevel;
		}

		internal Guid Id
		{
			get { return _id; }
		}

		internal int? ServerId
		{
			get { return _serverId; }
		}

		internal int? FolderId
		{
			get { return _folderId; }
		}

		internal Uri SourceUrl
		{
			get { return this.Attributes[Osh.Media.MediaAttributeNames.SourceUrl] as Uri; }
			set { this.Attributes[Osh.Media.MediaAttributeNames.SourceUrl] = value; }
		}

		internal string LogoId
		{
			get { return _logoId; }
			set
			{
				_logoId = value;
				if(!string.IsNullOrEmpty(value))
					this.Attributes[Osh.Media.MediaAttributeNames.ChannelLogoUrl] =
						(this.Library as ChannelDatabase).Client.CreateChannelLogoUrl(value);
			}
		}

		internal int? AudioIndex
		{
			get { return (int?)this.Attributes[Osh.Media.MediaAttributeNames.AudioIndex]; }
			set { this.Attributes[Osh.Media.MediaAttributeNames.AudioIndex] = value; }
		}

		internal int? VolumeLevel
		{
			get { return (int?)this.Attributes[Osh.Media.MediaAttributeNames.VolumeLevel]; }
			set { this.Attributes[Osh.Media.MediaAttributeNames.VolumeLevel] = value; }
		}

		public override ChannelEpg GetEpg(DateTime startTime, DateTime endTime)
		{
			return (this.Library as ChannelDatabase).Client.EpgParser.GetChannelEpg(this, startTime, endTime);
		}

		internal void Update(Channel newChannel)
		{
			this.SourceUrl = newChannel.SourceUrl;
			this.Name = newChannel.Name;
			this.Description = newChannel.Description;
			this.LogoId = newChannel.LogoId;
		}

		private static Uri CreateChannelUri(Guid id)
		{
			return new Uri("qwerty.ru:" + id.ToString());
		}
	}
}
